<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
<!--      <el-form-item label="服务名称" prop="fwName">-->
<!--        <el-input-->
<!--          v-model="queryParams.fwName"-->
<!--          placeholder="请输入服务名称"-->
<!--          clearable-->
<!--          size="small"-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item prop="phone" label="开发者">
        <el-select v-model="queryParams.phone" clearable filterable placeholder="请选择开发者">
          <el-option
            v-for="dict in phoneOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="enterprise" label="所属企业">
        <el-select v-model="queryParams.enterprise" clearable filterable placeholder="请选择所属企业">
          <el-option
            v-for="dict in enterpriseOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="使用状态" prop="dataLevel">
        <el-select v-model="queryParams.dataLevel" placeholder="请选择使用状态" size="small" style="width: 160px">
          <el-option
            v-for="dict in dataLevelOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <!--<el-form-item label="服务省份" prop="serviceProvince">
        <el-input
          v-model="queryParams.serviceProvince"
          placeholder="请输入服务省份"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>-->
<!--      <el-form-item label="服务城市" prop="serviceCity">-->
<!--        <el-input-->
<!--          v-model="queryParams.serviceCity"-->
<!--          placeholder="请输入服务城市"-->
<!--          clearable-->
<!--          size="small"-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->

<!--      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
		  plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['webservice:trackservice:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
		  plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['webservice:trackservice:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
		  plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['webservice:trackservice:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['webservice:trackservice:import']"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
		  plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['webservice:trackservice:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-video-play"
          size="mini"
          :disabled="multiple"
          @click="handleStatus(true)"
          v-hasPermi="['datafactory:work:edit']"
        >启用
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-video-pause"
          size="mini"
          :disabled="multiple"
          @click="handleStatus(false)"
          v-hasPermi="['datafactory:work:edit']"
        >禁用
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="trackserviceList" @selection-change="handleSelectionChange"
              :height="this.tableHeight" border :default-sort = "{prop: 'priority', order: 'ascending'}">
      <el-table-column type="selection" width="55" align="center" />
<!--      <el-table-column label="编号" align="center" prop="id" />-->
<!--      <el-table-column label="服务名称" align="center" prop="fwName" />-->
<!--      :formatter="keyFormat"-->
      <!--<el-table-column label="轨迹服务ID" align="center" prop="serviceId" />-->
      <!--<el-table-column label="省份" align="center" prop="serviceProvince" :formatter="provinceFormat" />-->
<!--      <el-table-column label="城市" align="center" prop="serviceCity" :formatter="cityFormat" />-->
<!--      <el-table-column label="区县" align="center" prop="serviceDistrict" :formatter="districtFormat" />-->
      <!--<el-table-column label="描述" align="center" prop="serviceDesc" />
      <el-table-column label="创建人编号" align="center" prop="creatorId" />
      <el-table-column label="创建人姓名" align="center" prop="creatorName" />-->
      <el-table-column label="所属企业" align="center" prop="enterprise" :formatter="enterpriseFormat"/>
      <el-table-column label="开发者" align="center" prop="developer" />
      <el-table-column label="电话" align="center" prop="phone" />
      <el-table-column label="高德密码" align="center" prop="password"  />
      <el-table-column label="高德key" align="center" prop="gaodeKey"  />
      <el-table-column label="围栏数量" width="90px" align="center" prop="fenceNum" />
      <el-table-column label="优先级" width="90px" align="center" sortable prop="priority" />
      <el-table-column label="创建日期" align="center" prop="createDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="数据级别" width="100px" align="center" prop="dataLevel" :formatter="dataLevelFormat" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['webservice:trackservice:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['webservice:trackservice:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改轨迹服务配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="开发者名称" prop="developer">
          {{form.developer}}
        </el-form-item>
        <el-form-item label="开发者电话" prop="phone">
          <el-select v-model="form.phone" filterable placeholder="请选择电话号码" @change="setDeveloper">
            <el-option
              v-for="dict in phoneOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属企业" prop="enterprise">
          <el-select v-model="form.enterprise" placeholder="请选择所属企业">
            <el-option
              v-for="dict in enterpriseOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="高德密码" prop="password">
          <el-input v-model="form.password" placeholder="请输入密码"></el-input>
        </el-form-item>
<!--        <el-form-item label="服务名称" prop="fwName">-->
<!--          <el-input v-model="form.fwName" placeholder="请输入服务名称" />-->
<!--        </el-form-item>-->
        <el-form-item label="高德key" prop="gaodeKey">
          <el-input v-model="form.gaodeKey" placeholder="请输入Key"/>
<!--          <el-select v-model="form.gaodeKey" placeholder="请选择key" filterable @change="isDisableCity = false">-->
<!--            <el-option-->
<!--              v-for="dict in keyOptions"-->
<!--              :key="dict.dictValue"-->
<!--              :label="dict.dictLabel"-->
<!--              :value="dict.dictValue"-->
<!--            ></el-option>-->
<!--          </el-select>-->
        </el-form-item>

        <!--<el-form-item label="省份" prop="serviceProvince">
          <el-select v-model="form.serviceProvince" placeholder="请选择服务省份">
            <el-option
              v-for="dict in provinceOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>-->
<!--        <el-form-item label="城市" prop="serviceCity">-->
<!--          <el-select v-model="form.serviceCity" placeholder="请选择服务区县" :disabled="isDisableCity" @change="getDistrict">-->
<!--            <el-option-->
<!--              v-for="dict in cityOptions"-->
<!--              :key="dict.dictValue"-->
<!--              :label="dict.dictLabel"-->
<!--              :value="dict.dictValue"-->
<!--            ></el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->

<!--        <el-form-item label="区县" prop="serviceDistrict">-->
<!--          <el-select v-model="form.serviceDistrict" placeholder="请选择区县" @change="getStreet">-->
<!--            <el-option-->
<!--              v-for="district in district"-->
<!--              :key="district.adcode"-->
<!--              :label="district.name"-->
<!--              :value="district.adcode"-->
<!--            ></el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->

        <!--<el-form-item label="描述信息" prop="serviceDesc">
          <el-input
            type="textarea"
            :rows="2"
            placeholder="请输入内容"
            value=""
            v-model="form.serviceDesc">
          </el-input>
        </el-form-item>-->
<!--        <el-form-item label="数据级别" prop="dataLevel">-->
<!--          <el-select v-model="form.dataLevel" placeholder="请选择数据级别">-->
<!--            <el-option-->
<!--              v-for="dict in dataLevelOptions"-->
<!--              :key="dict.dictValue"-->
<!--              :label="dict.dictLabel"-->
<!--              :value="parseInt(dict.dictValue)"-->
<!--            ></el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px">
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <span class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</span>
          <el-link type="info" style="font-size:12px" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listTrackservice, getTrackservice, delTrackservice, addTrackservice, updateTrackservice, getDistrictByCity, updateUseStatus} from "@/api/integration/trackservice";
import {getToken} from "@/utils/auth";

export default {
  name: "Trackservice",
  components: {
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 是否禁用城市查询区县
      isDisableCity: true,
      // 轨迹服务配置表格数据
      trackserviceList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 用户导入参数
      upload: {
        // 是否显示弹出层（）
        open: false,
        // 弹出层标题（）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/webservice/trackservice/importData"
      },
      // 平台ID字典
      keyOptions: [],
      // 数据级别字典
      dataLevelOptions: [],
      provinceOptions: [],
      cityOptions: [],
      districtOptions: [],
      enterpriseOptions:[],
      phoneOptions:[],
      district:[],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        fwName: null,
        key: null,
        serviceId: null,
        dataLevel: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        fwName:[
          { required: true, message: "填写服务名字", trigger: "blur" }
        ],
        serviceCity:[
          { required: true, message: "请选择服务城市", trigger: "blur" }
        ],
        serviceDistrict:[
          { required: true, message: "请选择服务区县", trigger: "blur" }
        ],
        gaodeKey:[
          { required: true, message: "请输入key", trigger: "blur" }
        ],
        phone:[
          {required: true, message: "请输入电话号码", trigger: "blur"},
          { pattern:/^1[3|4|5|7|8][0-9]{9}$/, message: '电话号码格式不正确' }
        ],
        password: [
          {required: true, message: "请输入密码", trigger: "blur"}
        ],
        enterprise: [
          {required: true, message: "请选择所属企业", trigger: "blur"}
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getDicts("gaode_key").then(response => {
      this.keyOptions = response.data;
      console.log(this.keyOptions);
    });
    this.getDicts("data_level").then(response => {
      this.dataLevelOptions = response.data;
    });
    this.getDicts("province").then(response => {
      this.provinceOptions = response.data;
    });
    this.getDicts("city").then(response => {
      this.cityOptions = response.data;
    });
    this.getDicts("district").then(response => {
      this.districtOptions = response.data;
    });
    this.getDicts("enterprise_type").then(response => {
      this.enterpriseOptions = response.data;
    });
    this.getDicts("developer_type").then(response => {
      this.phoneOptions = response.data;
    });
    this.tableHeight = (document.body.offsetHeight)-270
  },
  methods: {
    /** 查询轨迹服务配置列表 */
    getList() {
      this.loading = true;
      listTrackservice(this.queryParams).then(response => {
        this.trackserviceList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 平台ID字典翻译
    keyFormat(row, column) {
      return this.selectDictLabel(this.keyOptions, row.gaodeKey);
    },
    // 数据级别字典翻译
    dataLevelFormat(row, column) {
      return this.selectDictLabel(this.dataLevelOptions, row.dataLevel);
    },
    cityFormat(row, column) {
      return this.selectDictLabel(this.cityOptions, row.serviceCity);
    },
    districtFormat(row, column) {
      return this.selectDictLabel(this.districtOptions, row.serviceDistrict);
    },
    provinceFormat(row, column) {
      return this.selectDictLabel(this.provinceOptions, row.serviceProvince);
    },
    enterpriseFormat(row, column) {
      return this.selectDictLabel(this.enterpriseOptions, row.enterprise);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.isDisableCity = true
      this.form = {
        id: null,
        fwName: null,
        key: null,
        serviceId: null,
        creatorId: null,
        creatorName: null,
        createDate: null,
        dataLevel: null,
        developer: null,
        phone: null,
        password: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加轨迹服务配置";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      this.isDisableCity = false
      getTrackservice(id).then(response => {
        this.form = response.data;
        // getDistrictByCity(response.data).then(response=>{
        //   this.district = response.data;
        // })
        this.open = true;
        this.title = "修改轨迹服务配置";
      });
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "表导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('webservice/trackservice/importTemplate', {
        ...this.queryParams
      }, `track_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    /** 根据电话赋值开发者名称 */
    setDeveloper(value){
      this.phoneOptions.forEach(item =>{
        if(item.dictValue == value){
          this.form.developer = item.dictLabel
        }
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.districtOptions.forEach(item => {
            if (this.form.serviceDistrict == item.serviceDistrict) {
              this.form.adcodeName = item.name;
            }
          });
          if (this.form.id != null) {
            updateTrackservice(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTrackservice(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除轨迹服务配置编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delTrackservice(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('webservice/trackservice/export', {
        ...this.queryParams
      }, `webservice_trackservice.xlsx`)
    },
    /** 使用或禁用状态更新 */
    handleStatus(isStart) {
      this.isStart = isStart;
      let statusNo = 0;
      if (isStart === true) {
        var status = '启动';
        statusNo = 1;
      } else {
        status = '禁用';
        statusNo = 2;
      }
      const workIds = this.ids;
      this.$confirm('是否' + status + '"' + workIds + '"的数据项?', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return updateUseStatus(workIds, statusNo);
      }).then(() => {
        this.getList();
        this.msgSuccess(status + '成功')
      })
    },
    getDistrict(value){
      var data ={};
      data.serviceCity = value;
      data.gaodeKey = this.form.gaodeKey
      this.cityOptions.forEach(item =>{
        if(value==item.dictValue){
          data.serviceCity = item.dictLabel;
          this.form.serviceCity = item.dictValue;
        }
      })
      getDistrictByCity(data).then(response=>{
        this.district = response.data;
      })
    },
    getStreet(value){
      var data = {};
      data.serviceDistrict = value;
      data.gaodeKey = this.form.gaodeKey
      console.log(data)
    }
  }
};
</script>
